<template>
  <s-clean-layout title="事件">
    <view class="event-container">
      <!-- 搜索框 -->
      <view class="search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input 
          class="search-input" 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索联系人、事件、日期" 
          @input="handleSearch"
        />
      </view>

      <!-- 分类标签 -->
      <view class="category-tabs">
        <view 
          class="tab-item" 
          :class="{ active: selectedCategory === '' }"
          @tap="selectCategory('')"
        >全部</view>
        <view 
          class="tab-item" 
          v-for="(category, index) in categoryList" 
          :key="index"
          :class="{ active: selectedCategory === category }"
          @tap="selectCategory(category)"
        >
          <text>{{ category }}</text>
        </view>
      </view>

      <view class="empty-tip" v-if="filteredEvents.length === 0">
        <image class="empty-icon" src="/static/data-empty.png" mode="aspectFit"></image>
        <text class="empty-text">暂无事件数据</text>
      </view>

      <view 
        class="event-card" 
        v-for="(event, index) in filteredEvents" 
        :key="event.id"
        @tap="onEventClick(event)"
      >
        <view class="event-header">
          <view class="user-info">
            <image v-if="event.img && event.img !== ''" class="user-avatar" :src="event.img" mode="aspectFill" @error="handleImageError(event)"></image>
            <text class="user-name" :class="{'no-avatar': !event.img || event.img === ''}">{{ event.name }}</text>
          </view>
          <view class="event-tags">
            <view class="event-tag type-tag">
              <text>{{ event.type || getCategoryName(event.categoryId) }}</text>
            </view>
            <view class="event-tag" :class="getStatusClass(event.dealStatus)">
              {{ getStatusText(event.dealStatus) }}
            </view>
          </view>
        </view>
        
        <view class="event-content">
          <view class="event-title">{{ event.eventName }}</view>
        </view>
        
        <view class="event-footer">
          <text class="event-time">{{ formatEventDate(event.eventDate) }}</text>
          <view class="event-info">
            <view class="event-reminder" v-if="event.reminderEnabled === 1">
              <uni-icons type="notification" size="12" color="#999"></uni-icons>
              <text>{{ formatReminder(event) }}</text>
            </view>
            <view class="event-repeat" v-if="event.repeatType > 0">
              <uni-icons type="loop" size="12" color="#999"></uni-icons>
              <text>{{ getRepeatTypeText(event.repeatType) }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <view class="add-button" @tap="addEvent">
        <uni-icons type="plusempty" size="24" color="#FFFFFF"></uni-icons>
      </view>
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import EventApi from '@/pages/contact/api/event';

// 本地事件列表
const localEvents = ref([]);
// 添加加载状态标记，防止重复加载
const isLoading = ref(false);
// 添加上次加载时间标记
const lastLoadTime = ref(0);
// 搜索关键词
const searchKeyword = ref('');
// 选中的分类
const selectedCategory = ref('');
// 分类列表
const categoryList = ref([]);

// 计算属性：获取显示的事件列表
const displayEvents = computed(() => {
  return localEvents.value || [];
});

// 计算属性：获取过滤后的事件列表
const filteredEvents = computed(() => {
  let events = displayEvents.value;
  
  // 按分类筛选
  if (selectedCategory.value) {
    events = events.filter(event => event.type === selectedCategory.value);
  }
  
  // 按关键词筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    events = events.filter(event => 
      event.eventName.toLowerCase().includes(keyword) || 
      event.eventContent.toLowerCase().includes(keyword) ||
      event.name.toLowerCase().includes(keyword)
    );
  }
  
  return events;
});

// 处理搜索
const handleSearch = () => {
  // 搜索逻辑已经在计算属性中处理
};

// 选择分类
const selectCategory = (category) => {
  selectedCategory.value = category;
};

// 加载事件列表
const loadEvents = async () => {
  if (isLoading.value) return;
  
  try {
    isLoading.value = true;
    
    const res = await EventApi.queryContactEvents({});
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      // 转换API返回的数据格式为组件需要的格式
      localEvents.value = res.data.map(item => {
        return {
          ...item,
          // UI展示所需的额外字段
          img: item.contactImg || '', // 联系人头像
          name: item.contactName || '发起人', // 联系人名称
          type: item.categoryName || getCategoryName(item.categoryId),
          title: item.eventName,
          description: item.eventContent,
          status: getStatusText(item.dealStatus),
          statusClass: getStatusClass(item.dealStatus),
          date: formatEventDate(item.eventDate)
        };
      });
      
      // 提取所有分类
      const categories = new Set(localEvents.value.map(event => event.type));
      categoryList.value = Array.from(categories).filter(Boolean);
      
      // 记录本次加载时间
      lastLoadTime.value = Date.now();
    } else {
      localEvents.value = [];
      categoryList.value = [];
      uni.showToast({
        title: res.msg || '获取事件列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取事件列表失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 点击事件卡片，跳转到事件编辑页面
const onEventClick = (event) => {
  uni.navigateTo({
    url: `/pages/contact/event-edit?id=${event.id}&contactId=${event.contactId || ''}&mode=edit&contactName=${encodeURIComponent(event.name)}&contactImg=${encodeURIComponent(event.img || '')}`
  });
};

// 添加新事件
const addEvent = () => {
  uni.navigateTo({
    url: `/pages/contact/event-edit?mode=add`
  });
};

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  if (!categoryId) return '读书';
  
  const categories = uni.getStorageSync('eventCategories');
  if (categories && Array.isArray(categories)) {
    const category = categories.find(item => item.id === categoryId);
    if (category) return category.name;
  }
  
  return '读书';
};

// 根据状态获取样式类名
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-pending',    // 未完成
    1: 'status-completed',  // 已完成
    2: 'status-abandoned'   // 已放弃
  };
  
  return classMap[status] || '';
};

// 根据状态获取文本
const getStatusText = (status) => {
  const textMap = {
    0: '未完成',
    1: '已完成',
    2: '已放弃'
  };
  
  return textMap[status] || '未完成';
};

// 格式化事件日期
const formatEventDate = (timestamp) => {
  if (!timestamp) return '';
  
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 格式化提醒信息
const formatReminder = (event) => {
  if (event.reminderEnabled !== 1) return '不提醒';
  
  const days = event.advanceReminderDays || 0;
  const time = event.advanceReminderTime ? event.advanceReminderTime.substring(0, 5) : '09:00';
  
  if (days === 0) {
    return `当天 ${time}`;
  } else {
    return `提前${days}天 ${time}`;
  }
};

// 获取重复类型文本
const getRepeatTypeText = (repeatType) => {
  const typeMap = {
    0: '不重复',
    1: '每天',
    2: '每周',
    3: '每月',
    4: '每年'
  };
  
  return typeMap[repeatType] || '不重复';
};

// 处理图片加载错误
const handleImageError = (event) => {
  event.img = '';
};

onMounted(() => {
  loadEvents();
});

onShow(() => {
  loadEvents();
});

onPullDownRefresh(() => {
  loadEvents().finally(() => {
    uni.stopPullDownRefresh();
  });
});
</script>

<style lang="scss" scoped>
.event-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100%;
  position: relative;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #FFFFFF;
  border-radius: 8rpx;
  padding: 16rpx 20rpx;
  margin-bottom: 20rpx;
  
  .search-input {
    flex: 1;
    margin-left: 16rpx;
    font-size: 14px;
    color: #333;
    
    &::placeholder {
      color: #999;
    }
  }
}

.category-tabs {
  display: flex;
  padding: 16rpx 20rpx;
  background-color: #fff;
  overflow-x: auto;
  white-space: nowrap;
  margin-bottom: 20rpx;
}

.tab-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8rpx 20rpx;
  margin-right: 16rpx;
  background-color: #f5f5f5;
  border-radius: 24rpx;
  font-size: 24rpx;
  color: #666;
}

.tab-item.active {
  background-color: #ff6000;
  color: #fff;
}

.event-card {
  margin: 0 20rpx 16rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.event-card:first-child {
  margin-top: 0;
}

.event-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 24rpx;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  margin-right: 16rpx;
}

.user-name {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.no-avatar {
  margin-left: 0;
}

.event-tags {
  display: flex;
  gap: 12rpx;
}

.event-tag {
  display: flex;
  align-items: center;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  font-size: 12px;
  gap: 4rpx;
}

.type-tag {
  background-color: #F0F7FF;
  color: #007AFF;
}

.status-pending {
  background-color: #FFF0F0;
  color: #FF5252;
}

.status-abandoned {
  background-color: #F5F5F5;
  color: #666;
}

.status-completed {
  background-color: #F0FFF0;
  color: #4CAF50;
}

.event-content {
  padding: 0 24rpx 16rpx;
}

.event-title {
  font-size: 16px;
  color: #007AFF;
  font-weight: 500;
}

.event-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 24rpx;
  border-top: 1px solid #f0f0f0;
}

.event-time {
  font-size: 12px;
  color: #999;
}

.event-info {
  display: flex;
  gap: 16rpx;
}

.event-reminder, .event-repeat {
  display: flex;
  align-items: center;
  gap: 4rpx;
  font-size: 12px;
  color: #999;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.add-button {
  position: fixed;
  right: 40rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #007AFF;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
  z-index: 10;
}
</style>